package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"goods/goods"
	"goods/internal/svc"
	"goods/models/mysql"
	"goods/models/redisinit"
	"goods/pkg"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *goods.CreateOrderRequest) (*goods.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.Info(int(in.GoodsId))
	if err != nil {
		logx.Error("商品不存在")
		return nil, err
	}
	if g.GoodsStock < int(in.GoodsNum) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	orderSn := uuid.NewString()
	amount := g.GoodsPrice * float64(in.GoodsNum)
	o := mysql.Order{
		UserId:  int(in.UserId),
		OrderSn: orderSn,
		PayType: int(in.Payment),
		Status:  1,
		PayTime: 0,
		Amount:  amount,
	}

	og := mysql.OrderGoods{
		GoodsId:    int(in.GoodsId),
		GoodsTitle: g.GoodsTitle,
		Num:        int(in.GoodsNum),
		Price:      g.GoodsPrice,
		GoodsCover: g.GoodsCover,
	}
	err = mysql.CreateOrder(mysql.Db, &o, &og)
	if err != nil {
		logx.Error("创建订单失败")
		return nil, err
	}
	redisinit.DelGoodsSync(in.GoodsId, in.GoodsNum)
	s := fmt.Sprintf("%.2F", amount)
	alipay := pkg.AliPay{
		Subject:     "商品支付",
		OutTradeNo:  orderSn,
		TotalAmount: s,
	}
	url := alipay.Pay()
	return &goods.CreateOrderResponse{
		PayUrl:  url,
		OrderId: int64(o.ID),
	}, nil

}
